package com.example.system.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.domain.R;
import com.example.common.core.enums.ResultCode;
import com.example.system.domain.SysAdmin;
import com.example.system.mapper.ISysAdminMapper;
import com.example.system.services.ISysAdminServices;
import com.example.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2025-02-10
 * Time: 21:26
 */

// 服务端接口实现类
@Service
public class SysAdminServicesImpl implements ISysAdminServices {

    @Autowired
    private ISysAdminMapper sysAdminMapper;

    // 查询账号接口实现
    @Override
    public R<Void>login (String userAccount, String password) {
        LambdaQueryWrapper<SysAdmin> queryWrapper = new LambdaQueryWrapper<>();
        int t = 100/0;
        // 构建 Lambda 表达式
        // 1. queryWrapper.select 查询语句
        // 2. select(SysAdmin::getPassword) 根据密码去查询返回一条指定的泛型数据 SysAdmin
        // 3. eq(SysAdmin::getUserAccount, userAccount) 通过密码查询到一条数据后再比对该数据的 Account和传入的Account确定用户
        SysAdmin sysAdmin = sysAdminMapper.
                selectOne(queryWrapper.select(SysAdmin::getPassword).eq(SysAdmin::getUserAccount, userAccount));

//        R result = new R();
        // 处理返回结果
        // 1. 登录的用户不存在
        if (sysAdmin == null) {

//            result.setCode(ResultCode.FAILED_USER_NOT_EXISTS.getCode());
//            result.setMsg(ResultCode.FAILED_USER_NOT_EXISTS.getMsg());
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        // 2. 已确定存在用户名, 但密码不正确
        //    已经使用 BCrypt 加密, 无法使用 equals 简单进行比较
        if (!BCryptUtils.matchesPassword(password, sysAdmin.getPassword())) {
//            result.setCode(ResultCode.FAILED_LOGIN.getCode());
//            result.setMsg(ResultCode.FAILED_LOGIN.getMsg());
            return R.fail(ResultCode.FAILED_LOGIN);
        }

        // 3. 登录成功无需设置提示消息
        // result.setCode(ResultCode.SUCCESS.getCode());
        return R.ok();

    }
}
